package cn.e3mall.service.impl;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.pojo.EasyUIDataGridResult;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.common.utils.IDUtils;
import cn.e3mall.common.utils.JsonUtils;
import cn.e3mall.mapper.TbItemDescMapper;
import cn.e3mall.mapper.TbItemMapper;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbItemDesc;
import cn.e3mall.pojo.TbItemExample;
import cn.e3mall.service.ItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.*;
import java.util.Date;
import java.util.List;

/**
 * @author JiangBin
 * @version 1.0.0 @
 * @description 商品管理service
 * @date 2018年2月23日 下午9:54:41
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private TbItemMapper itemMapper;

    @Autowired
    private TbItemDescMapper itemDescMapper;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Resource(name = "itemAddTopic")
    private Destination destination;

    @Autowired
    private JedisClient jedisClient;

    @Value("${ITEM_INFO}")
    private String ITEM_INFO;

    @Value("${ITEM_EXPIRE}")
    private Integer ITEM_EXPIRE;

    @Override
    public E3Result getItemById(long itemId) {
        //查询数据库之前先查询缓存
        try {
            String json = jedisClient.get(ITEM_INFO + ":" + itemId + ":BASE");
            if (!StringUtils.isBlank(json)) {
                //把json数据转换成对象
                TbItem tbItem = JsonUtils.jsonToPojo(json, TbItem.class);
                return E3Result.ok(tbItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        TbItem item = itemMapper.selectByPrimaryKey(itemId);
        //把查询的结果添加到缓存中
        try {
            jedisClient.set(ITEM_INFO + ":" + itemId + ":BASE", JsonUtils.objectToJson(item));
            //设置过期时间
            jedisClient.expire(ITEM_INFO + ":" + itemId + ":BASE", ITEM_EXPIRE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return E3Result.ok(item);
    }

    @Override
    public E3Result getItemDescById(long itemId) {
        //1.在查询数据库之前查询缓存
        try {
            String json = jedisClient.get(ITEM_INFO + ":" + itemId + ":DESC");
            if(!StringUtils.isBlank(json)){
                //将json数据转换成对象
                TbItemDesc tbItemDesc = JsonUtils.jsonToPojo(json, TbItemDesc.class);
                return E3Result.ok(tbItemDesc);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //2.将从数据库查询的数据添加到缓存中
        TbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(itemId);
        try {
            jedisClient.set(ITEM_INFO + ":" + itemId + ":DESC", JsonUtils.objectToJson(itemDesc));
            //设置缓存时间
            jedisClient.expire(ITEM_INFO + ":" + itemId + ":DESC", ITEM_EXPIRE);
        }catch (Exception e){
            e.printStackTrace();
        }
        return E3Result.ok(itemDesc);
    }

    @Override
    public EasyUIDataGridResult getItemList(int page, int rows) {
        // 设置分页信息
        PageHelper.startPage(page, rows);
        // 执行查询
        TbItemExample example = new TbItemExample();
        List<TbItem> list = itemMapper.selectByExample(example);
        // 获取分页信息
        PageInfo<TbItem> pageInfo = new PageInfo<>(list);

        // 创建返回结果对象
        EasyUIDataGridResult result = new EasyUIDataGridResult();
        result.setTotal(pageInfo.getTotal());
        result.setRows(list);

        return result;
    }

    @Override
    public E3Result addItem(TbItem item, String desc) throws Exception {
        // 1.生成商品ID
        final long itemId = IDUtils.genItemId();
        // 2.补全Tbitem对象属性
        item.setId(itemId);
        // 商品状态，1-正常，2-下架，3-删除
        item.setStatus((byte) 1);
        Date date = new Date();
        item.setCreated(date);
        item.setUpdated(date);
        // 3.向商品表中插入数据
        itemMapper.insert(item);
        // 4.创建一个TbItemDesc对象
        TbItemDesc itemDesc = new TbItemDesc();
        // 5.补全TbItemDesc的属性
        itemDesc.setItemId(itemId);
        itemDesc.setItemDesc(desc);
        itemDesc.setCreated(date);
        itemDesc.setUpdated(date);
        // 6.向商品描述表插入数据
        itemDescMapper.insert(itemDesc);

        //发送activemq消息
        jmsTemplate.send(destination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage textMessage = session.createTextMessage(itemId + "");
                return textMessage;
            }
        });
        // 7.返回E3Result
        return E3Result.ok();
    }

    @Override
    public E3Result updateItem(TbItem item, String desc) {
        // 修改商品规格
        Date date = new Date();
        item.setUpdated(date);
        itemMapper.updateByPrimaryKey(item);

        // 修改商品详情
        TbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(item.getCid());
        itemDesc.setItemDesc(desc);
        itemDesc.setUpdated(date);
        itemDescMapper.updateByPrimaryKey(itemDesc);

        return E3Result.ok();
    }

    @Override
    public E3Result putUpItem(String[] itemIds) {
        for (String id : itemIds) {
            // 根据id查询商品信息并修改状态
            TbItem tbItem = itemMapper.selectByPrimaryKey(Long.valueOf(id));
            tbItem.setStatus((byte) 1);
            Date date = new Date();
            tbItem.setUpdated(date);
            itemMapper.updateByPrimaryKey(tbItem);
        }
        return E3Result.ok();
    }

    @Override
    public E3Result putOffItem(String[] itemIds) {
        for (String id : itemIds) {
            // 根据id查询商品信息并修改状态
            TbItem tbItem = itemMapper.selectByPrimaryKey(Long.valueOf(id));
            tbItem.setStatus((byte) 2);
            Date date = new Date();
            tbItem.setUpdated(date);
            itemMapper.updateByPrimaryKey(tbItem);
        }
        return E3Result.ok();
    }

    @Override
    public E3Result deleteItem(String[] itemIds) {
        for (String id : itemIds) {
            // 根据id查询商品信息并修改状态
            TbItem tbItem = itemMapper.selectByPrimaryKey(Long.valueOf(id));
            tbItem.setStatus((byte) 3);
            Date date = new Date();
            tbItem.setUpdated(date);
            itemMapper.updateByPrimaryKey(tbItem);
        }
        return E3Result.ok();
    }

}
